// 此组件是：推荐老师列表 组件
// this.props.dataList 是接受的父组件 传过来的 数据，进行遍历
import React from 'react';
import {
    Text,
    View,
    StyleSheet,
    Image,
    FlatList,
    TouchableOpacity,
    TouchableWithoutFeedback,
    BackHandler
} from 'react-native';
var Dimensions = require('Dimensions');
var { width } = Dimensions.get('window');
import { insertFllow, deleteFllow } from '../api/my';
import { Toast } from 'teaset';
import {setSpText,setHW} from './ScreenUtil'
export default class RecommendTea extends React.Component {
    // 初始化模拟数据
    constructor(props) {
        super(props);
        this.state = {
            isRefreshing: false,
            isFetching:false
        }
    }
    _footer = () => (
        <View>
            {this.props.loading ? <View style={styles.loadingMore}>
                <Text style={{ fontSize:setSpText(28), alignSelf: 'center' }}>{this.props.hasMore ? '加载更多' : '到底啦， 没有啦！'}</Text>
            </View> : null}
        </View>
    )
    render() {
        //  {/* 0是没关注 1是已经关注 */}
        return (
            <View style={styles.itemBox}>
                <FlatList
                    data={this.props.TeacherList}
                    extraData={this.state}
                    initialNumToRender={10}
                    renderItem={({ item }) => this.renderItem(item)}
                    keyExtractor={(item, index) => index}
                    onEndReachedThreshold={20}
                />
            </View>
        );
    }
    // 跳转到 教师详情页面
    goTeaIntro(item) {
        let that=this;
        this.props.navigation.navigate('TeaIntroduction', 
        { 
            teacherId: item.USERID,
            refreshPage: function () {
                that.props.reSearchData&&that.props.reSearchData()
			}
        });
        if (this.props && this.props.navigation && this.props.navigation.pressBack) {
            BackHandler.removeEventListener('hardwareBackPress', this.props.navigation.pressBack)
        }
    }
    
    renderItem(item) {
        // console.log(item,'item item item item item item item');
        if (this.props.noGo) {//点击不需要跳转到老师详情(老师介绍组件页面的展示)
            return (
                <View key={item.USERID}
                    style={[styles.item,{ marginBottom: 0 }]}>
                    <View style={styles.itemLeft}>
                        {this.headerIcon(item)}
                    </View>
                    <View style={styles.itemRight}>
                        <View style={styles.rightTop}>
                            <View style={styles.teacher}>
                                <Text style={styles.teacherText}>{this.MoreText(item.NAME, 4)}</Text>
                            </View>
                            {this.careFun(item)}
                        </View>
                        <View style={styles.rightBottom}>
                            <Text style={styles.infor}>{this.MoreText(item.SELFINTRODUCTION, 100)}</Text>
                        </View>
                    </View>
                </View>
            )
        } else {//点击会跳转到老师详情页
            return (
                <TouchableOpacity key={item.USERID}
                    style={[styles.item,{ marginBottom: 5 }]}
                    onPress={() => this.goTeaIntro(item)}>
                    <View style={styles.itemLeft}>
                        {this.headerIcon(item)}
                    </View>
                    <View style={styles.itemRight}>
                        <View style={styles.rightTop}>
                            <View style={styles.teacher}>
                                <Text style={styles.teacherText}>{this.MoreText(item.NAME, 4)}</Text>
                            </View>
                            {this.careFun(item)}
                        </View>
                        <View style={styles.rightBottom}>
                            <Text style={styles.infor}>{this.MoreText(item.SELFINTRODUCTION, 100)}</Text>
                        </View>
                    </View>
                </TouchableOpacity>
            )
        }
    }
    // 字体超出限制
    MoreText(text, MaxNum) {
        //替换所有的换行符
        text = text.replace(/\r\n/g,"")
        text = text.replace(/\n/g,"");
        //替换所有的空格（中文空格、英文空格都会被替换）
        text = text.replace(/\s/g,"");
        if (text) {
            if (text.length > MaxNum) {
                return (
                    text.substring(0, MaxNum) + '...'
                )
            } else {
                return (
                    text
                )
            }
        }
    }
    // 显示老师名称，最多10个字符，多出字符使用省略号表示
    // 头像
    headerIcon(item){
        if(item.HEADPORTRAIT&&item.HEADPORTRAIT!=='null'){
            return(
                <Image style={styles.teacherIcon} source={{
                    uri: this.handleImage(item.HEADPORTRAIT)}} />
            )
        }else{
            return(
                <Image style={styles.teacherIcon} source={require('../assets/imgs/default.png')}/>
            )
        }
    }
    handleImage(imgUrl) {
        // http://dfs.img.jzexueyun.com/elearning/20180911/dc129d1747b04965b4f2f75f569074cc.jpg
        // console.log(imgUrl.replace('http://dfs.img.jzexueyun.com', 'http://dfs.view-img.jzexueyun.com') + '?imageView2/2/w/260/')
        return imgUrl.replace('http://dfs.img.jzexueyun.com', 'http://dfs.view-img.jzexueyun.com') + '?imageView2/2/w/260/';
    }
    // 展示关注按钮 有ISFLLOW字段再根据 它的值 显示关注  {/* 0是没关注 1是已经关注 */}
    // 我的-我的关注页面 关注接口是 hadFellow=='1'，只有已关注状态
    careFun(item) {
        if (item.ISFLLOW) {
            if(item.ISFLLOW!=='-1'){
                return (
                    <TouchableWithoutFeedback onPress={() => this.onClickIsCare(item.ISFLLOW, item)}>
                        <View style={[item.ISFLLOW == '0'?styles.goCare:styles.disCareText]}>
                            <Text style={styles.careText}>
                                {item.ISFLLOW == '0' ? '+ 关注' : '已关注'}
                            </Text>
                        </View>
                    </TouchableWithoutFeedback>
                )
            }else{//拉黑
                return (
                    <View style={styles.disCareText}>
                        <Text style={styles.careText}>+ 关注</Text>
                    </View>
                )
            }
        } else {
            if (item.hadFellow == '1') {//我的关注页面
                return (
                    <TouchableWithoutFeedback onPress={() => this.onClickIsCare(item.hadFellow, item)}>
                         <View style={styles.disCareText}>
                            <Text style={styles.careText}>已关注</Text>
                        </View>
                    </TouchableWithoutFeedback>
                )
            }
        }
    }
    // 是否关注
    onClickIsCare(status,item){
        this.setState({
            isFetching:!this.state.isFetching
        });
        if(item.ISFLLOW){
            item.ISFLLOW=status=='0'?'1':'0';
        }
        let json={
            "USER_ID": global.ECourseConstant.userInfo.uuid,//用户id
            "TEACHER_ID": item.USERID
        }
        if (status == '0') {//没有关注-- 去关注
            insertFllow(json).then(() => {
                Toast.message("关注成功")
            })
        } else {//取消关注 有的页面是取消关注不是更改按钮状态 而是从列表中删除
            
            !this.props.from&&this.props.reSearchData&&this.deleteOne(item);//手动删除当前项
            deleteFllow(json).then(() => {
                Toast.message("取消关注成功")
                if(this.props.TeacherList.length==0){
                    this.props.reSearchData&&this.props.reSearchData()
                }
            })
        }
    }
    // 删除取消关注的那一条
    deleteOne(item){
        let id=item.ID;
        let itemIndex=null;
        this.props.TeacherList.forEach((item,index)=>{
            item.ID==id?itemIndex=index:null
        })
        this.props.TeacherList.splice(itemIndex,1)
    }
}

const styles = StyleSheet.create({
    loadingMore: {
        height: setHW(60),
        justifyContent: 'center',
        alignItems: 'center'
    },
    itemBox: {
        flexDirection: 'row',
        flexWrap: 'wrap',
        alignItems: 'flex-start',
        backgroundColor: '#F7F7F9',
    },
    item: {
        padding:  setHW(30),
        flexDirection: 'row',
        backgroundColor: '#fff',
        justifyContent: 'space-between'
    },
    itemLeft: {
        width:setHW(156),
        marginRight:setHW(20),
    },
    teacherIcon: {
        width: setHW(156),
        height: setHW(208),
    },
    itemRight: {
        width: width - setHW(236),
    },
    rightTop: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        height:setHW(52),
        alignItems:'center',
    },
    goCare: {
        backgroundColor: '#FF8A00',
        borderRadius: setHW(40),
        height:setHW(44),
        justifyContent:'center',
        alignItems:'center',
        paddingRight: setHW(24),
        paddingLeft: setHW(24),
    },
    disCareText: {
        backgroundColor: '#ccc',
        borderRadius: setHW(40),
        height:setHW(44),
        justifyContent:'center',
        alignItems:'center',
        paddingRight: setHW(24),
        paddingLeft: setHW(24),
    },
    careText:{
        fontSize:setSpText(26),
        color: '#fff',
    },
    teacherText: {
        fontWeight: 'bold',
        fontSize:setSpText(30),
        color: '#333'
    },
    teacherSchool: {
        fontSize:setSpText(24),
        marginBottom: setHW(18),
    },
    infor: {
        fontSize:setSpText(26),
        color: '#666',
        lineHeight: setSpText(38),
    },
    rightBottom: {
        marginTop: setHW(6),
    }
});
